﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Entities;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;
using WeatherHistory.Shared.Helpers;

namespace WeatherHistory.Api.CommandsQueries.Commands.Accounts.Registration;

public class RegistrationAccountsCommandHandler : IRequestHandler<RegistrationAccountsCommandRequest, RegistrationAccountsCommandResponse>
{
    private readonly IAccountRepository _accountRepository;
    private readonly IMapper _mapper;

    public RegistrationAccountsCommandHandler(IMapper mapper, IAccountRepository accountRepository)
    {
        _mapper = mapper;
        _accountRepository = accountRepository;
    }

    public async Task<RegistrationAccountsCommandResponse> Handle(RegistrationAccountsCommandRequest request, CancellationToken cancellationToken)
    {
        var emailRegistered = await _accountRepository.AnyAsync(x => x.Email == request.Email.ToLower(), cancellationToken);
        if (emailRegistered) throw new ConflictException("Пользователь с таким email уже зарегистрирован");

        var newAccount = new Account();
        newAccount.Email = request.Email.ToLower();
        newAccount.FirstName = request.FirstName;
        newAccount.LastName = request.LastName;
        newAccount.PasswordHash = SecurityHelper.ComputeSha256Hash(request.Password);

        await _accountRepository.InsertAsync(newAccount, cancellationToken);

        return _mapper.Map<RegistrationAccountsCommandResponse>(newAccount);
    }
}